package com.qf.j2112.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;

/**
 * @ProjectName: YiZhanXiYi
 * @Package: com.qf.j2112.utils
 * @ClassName: JwtUtil
 * @Author: 宋晓博
 * @Description: description
 * @Date: 2022/4/13 19:37
 * @Version: 1.0
 */
public class JwtUtil {

    private final  static  String SECRET="j2112";

    //创建新令牌
    public  static  String getToken(String userName){
        long expire=System.currentTimeMillis()+10*60*1000;
        Date date = new Date(expire);
        JWTCreator.Builder builder= JWT.create();
        builder.withExpiresAt(date);
        builder.withClaim("userName",userName);
        //builder.withClaim("userId",001);
        //根据密钥创建一个指定算法对象
        Algorithm hmac256 = Algorithm.HMAC256(SECRET );
        //根据指定算法，载荷信息，生存期，进行签名（加密）
        String sign = builder.sign(hmac256);
        return sign;
    }

    //校验令牌
    public static boolean verifyToken(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier jwtVerifier = JWT.require(algorithm).build();
            DecodedJWT verify = jwtVerifier.verify(token);
            return true;
        }catch (JWTVerificationException ex){
            return  false;
        }


    }

    //从合法的令牌中获取载荷信息
    public static String getUsrInfoFromToken(String Token){
        String s = JWT.decode(Token).getClaim("userName").asString();
        return s;
    }
}
